import json
import re

from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django.contrib.auth import login
from django.db import DatabaseError
from django.http import JsonResponse
from django.views import View
import logging

from django_redis import get_redis_connection

from carts.utils import merge_cart_cookie_to_redis
from oauth.models import OAuthQQUser
from oauth.utils import generate_access_token, check_access_token
from users.models import User

logger = logging.info('django')


class QQURLView(View):
    def get(self, request):
        next = request.GET.get('next')

        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)

        login_url = oauth.get_qq_url()

        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'login_url': login_url
        })


class QQUserView(View):

    def get(self, request):
        code = request.GET.get('code')

        if not code:
            return JsonResponse({
                'code': 400,
                'errmsg': '缺少code参数'
            })

        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)
        try:
            access_token = oauth.get_access_token(code)

            openid = oauth.get_open_id(access_token)
        except Exception as e:
            return JsonResponse({
                'code': 400,
                'errmsg': 'oauth2.0认证失败, 即获取qq信息失败'
            })
        try:
            oauth_qq = OAuthQQUser.objects.get(openid=openid)

        except OAuthQQUser.DoesNotExist:

            access_token = generate_access_token(openid)
            return JsonResponse({
                'code': 300,
                'errmsg': 'ok',
                'access_token': access_token
            })

        else:
            user = oauth_qq.user

            login(request, user)

            response = JsonResponse({
                'code': 0,
                'errmsg': 'ok'
            })
            response.set_cookie('username',
                                user.username,
                                max_age=3600 * 24 * 14)

            response = merge_cart_cookie_to_redis(request=request, user=user, response=response)

            return response

    def post(self, request):

        dict = json.loads(request.body.decode())

        mobile = dict.get('mobile')
        password = dict.get('password')
        sms_code = dict.get('sms_code')
        access_token = dict.get('access_token')

        if not all([mobile, password, sms_code, access_token]):
            return JsonResponse({
                'code': 400,
                'errmsg': '缺少必须参数'
            })

        if not re.match(r'1[3-9]\d{9}$', mobile):
            return JsonResponse({
                'code': 400,
                'errmsg': '手机号不对'
            })
        if not re.match(r'\w{8-20}', password):
            return JsonResponse({
                'code': 400,
                'errmsg': '密码格式不对'
            })
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)

        if sms_code_server is None:
            # if not sms_code_server
            return JsonResponse({
                'code': 400,
                'errmsg': '验证码失效'
            })

        if sms_code != sms_code_server.decode():
            return JsonResponse({
                'code': 400,
                'errmsg': '验证码错误'
            })
        openid = check_access_token(access_token)

        if not openid:
            return JsonResponse({
                'code': 400,
                'errmsg': '缺少openid'
            })
        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            user = User.objects.create_user(username=mobile,
                                            password=password,
                                            mobile=mobile)
        else:
            if not user.check_password(password):
                return JsonResponse({
                    'code': 400,
                    'errmsg': '输入的密码不正确'
                })
        try:
            OAuthQQUser.objects.create(openid=openid,
                                       user=user)
        except DatabaseError:
            return JsonResponse({
                'code': 400,
                'errmsg': '往数据库添加数据出错'
            })
        login(request, user)

        response = JsonResponse({
            'code': 0,
            'errmsg': 'ok'
        })

        response.set_cookie('username',
                            user.username,
                            max_age=3600 * 24 * 14)

        response = merge_cart_cookie_to_redis(request=request, user=user, response=response)

        return response
